/**   
 *    
 * 项目名称：SmartKungFuService   
 * 类名称：ExpListServlet   
 * 类描述：   体验功夫接口
 * 创建人：zhangl  
 * 创建时间：2016年9月26日 上午11:55:39   
 * 修改人：zhangl   
 * 修改时间：2016年9月26日 上午11:55:39   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.servlet;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.ExpReqPara;
import com.lst.entity.response.ExpResPara;
import com.lst.model.ClientNum;
import com.lst.model.MstGymnasium;
import com.lst.model.ProjectInfo;
import com.lst.service.ClientNumService;
import com.lst.service.MstGymnasiumService;
import com.lst.service.ProjectInfoService;
import com.lst.utils.CommFunUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: ExpListServlet
 * @Description: 体验功夫接口
 * @author zhangl
 * @date 2016年9月26日 上午11:55:39
 *
 */
public class ExpListServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private ProjectInfoService projectInfoService = ctx.getBean(ProjectInfoService.class);

	private MstGymnasiumService mstGymnasiumService = ctx.getBean(MstGymnasiumService.class);

	private ClientNumService clientNumService = ctx.getBean(ClientNumService.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);

		ExpResPara resPara = new  ExpResPara();

		try {
			ExpReqPara reqPara = getReqPara(request);

			if(isCheckField(reqPara,resPara)){
				Integer exptype = Integer.valueOf(reqPara.getExptype());
				Integer page = Integer.valueOf(reqPara.getPage());
				Integer pagesize = Integer.valueOf(reqPara.getPagesize());
				String clientid = reqPara.getUserid();

				Map<String, Object> expMap = new HashMap<String, Object>();

				expMap.put("enabled", true);
				expMap.put("isDeleted", false);					

				PageBounds pageBounds = new PageBounds(page,pagesize);

				//统计量
				Map<String, Object> map = new HashMap<String, Object>();

				if(CommCode.SYSTEM_CARESEL_RANGE_PRO.equals(exptype)){//体验活动

					expMap.put("orderByClause", "pi.istop desc,pi.updatedate desc");

					List<ProjectInfo> pros = projectInfoService.queryByList(expMap, pageBounds);					

					for(ProjectInfo pi: pros){
						String starttime = StringUtils.isEmpty(pi.getStartdate()) ? null : DateUtil.getFormatTime(pi.getStartdate(), DateUtil.ALL_DATETIME_SEPARATOR_SPOT);
						String endtime = StringUtils.isEmpty(pi.getEnddate()) ? null : DateUtil.getFormatTime(pi.getEnddate(), DateUtil.ALL_DATETIME_SEPARATOR_SPOT);
						pi.setStarttime(starttime);			
						pi.setEndtime(endtime);
						//收藏量
						Integer favoritenum = CommFunUtils.opNum(null, pi.getId(), CommCode.SYSTEM_CARESEL_RANGE_PRO, CommCode.SYSTEM_COUNT_FAVORITE, clientNumService);
						//分享量
						Integer sharenum = CommFunUtils.opNum(null, pi.getId(), CommCode.SYSTEM_CARESEL_RANGE_PRO, CommCode.SYSTEM_COUNT_SHARE, clientNumService);
						//浏览量
						expMap.clear();
						expMap.put("enabled", true);
						expMap.put("isDeleted", false);	
						expMap.put("numtype", CommCode.SYSTEM_COUNT_BROWSE);
						expMap.put("actid", pi.getId());
						expMap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_PRO);

						List<ClientNum> browselist = clientNumService.queryByList(expMap);

						Integer browsenum = 0;

						for(ClientNum c : browselist){
							browsenum += c.getNum() == null ? 0 : c.getNum();
						}
						pi.setFavoritenum(favoritenum);
						pi.setSharenum(sharenum);
						pi.setBrowsenum(browsenum);

						List<ClientNum> cns = null;

						if(!StringUtils.isEmpty(clientid)){

							map.put("enabled", true);
							map.put("isDeleted", false);
							map.put("clientid", Integer.valueOf(clientid));
							map.put("numtype",CommCode.SYSTEM_COUNT_FAVORITE);
							map.put("actid", pi.getId());
							map.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_PRO);

							cns = clientNumService.queryByList(map);
						}

						if(null==cns||cns.size()==0){
							pi.setIsFavorite(false);										
						}else{
							pi.setIsFavorite(true);
						}
					}
					resPara.setPros(pros);													

				} else{ //体验场馆

					expMap.put("orderByClause", "gym.istop desc,gym.updatedate desc");

					List<MstGymnasium> gyms = mstGymnasiumService.queryByList(expMap, pageBounds);

					for(MstGymnasium mg: gyms){

						//收藏量
						Integer favoritenum = CommFunUtils.opNum(null, mg.getId(), CommCode.SYSTEM_CARESEL_RANGE_GYM, CommCode.SYSTEM_COUNT_FAVORITE, clientNumService);
						//分享量
						Integer sharenum = CommFunUtils.opNum(null, mg.getId(), CommCode.SYSTEM_CARESEL_RANGE_GYM, CommCode.SYSTEM_COUNT_SHARE, clientNumService);
						//浏览量
						expMap.clear();
						expMap.put("enabled", true);
						expMap.put("isDeleted", false);	
						expMap.put("numtype", CommCode.SYSTEM_COUNT_BROWSE);
						expMap.put("actid", mg.getId());
						expMap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_GYM);

						List<ClientNum> browselist = clientNumService.queryByList(expMap);
						Integer browsenum = 0;

						for(ClientNum c : browselist){
							browsenum += c.getNum() == null ? 0 : c.getNum();
						}

						mg.setFavoritenum(favoritenum);
						mg.setSharenum(sharenum);
						mg.setBrowsenum(browsenum);

						List<ClientNum> cns = null;

						if(!StringUtils.isEmpty(clientid)){

							map.put("enabled", true);
							map.put("isDeleted", false);
							map.put("clientid", Integer.valueOf(clientid));
							map.put("numtype",CommCode.SYSTEM_COUNT_FAVORITE);
							map.put("actid", mg.getId());
							map.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_GYM);

							cns = clientNumService.queryByList(map);
						}

						if(null==cns||cns.size()==0){						
							mg.setIsFavorite(false);
						}else{
							mg.setIsFavorite(true);
						}
					}						
					resPara.setGyms(gyms);					
				}
				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);
			}

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
			logger.info(jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public ExpReqPara getReqPara(HttpServletRequest request) {

		ExpReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new ExpReqPara());

			reqPara = (ExpReqPara) baseRequest.clone();

			String exptype = request.getParameter("exptype");
			String page = request.getParameter("page");
			String pagesize = request.getParameter("pagesize");
			String userid = request.getParameter("userid");

			logger.info("reqPara exptype: " + exptype);
			logger.info("reqPara page: " + page);
			logger.info("reqPara pagesize: " + pagesize);
			logger.info("reqPara userid: " + userid);

			reqPara.setExptype(exptype);
			reqPara.setPage(page);
			reqPara.setPagesize(pagesize);
			reqPara.setUserid(userid);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		ExpReqPara expReqPara = (ExpReqPara) reqPara;
		ExpResPara expResPara = (ExpResPara) resPara;

		if (StringUtils.isEmpty(expReqPara.getExptype())) {
			expResPara.setCode(CommCode.M_A000000);
			expResPara.setMessage(CommCode.M_E000001);
		} else if(StringUtils.isEmpty(expReqPara.getPage())){
			expResPara.setCode(CommCode.M_A000000);
			expResPara.setMessage(CommCode.M_P000009);
		} else if(StringUtils.isEmpty(expReqPara.getPagesize())){
			expResPara.setCode(CommCode.M_A000000);
			expResPara.setMessage(CommCode.M_P000010);
		} else{
			flag = true;
		}
		return  flag;
	}
}
